<?php
// +----------------------------------------------------------------------
// | Created by Sublime: [ Conqweal ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~20223[chenjia] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.99dn.cn
// +----------------------------------------------------------------------
// | Author: Conqweal <150672834@qq.com>
// +----------------------------------------------------------------------
// | Date: 2021/12/22 0026
// +----------------------------------------------------------------------
// | Description:任务接口
// +----------------------------------------------------------------------
namespace app\api\controller;

use app\Api;
use app\api\library\Credit;
use app\api\model\Mission as cModel;
use app\api\model\MissionBrowse as browseModel;
use app\api\model\MissionComments as commentsModel;
use app\api\model\MissionEstimate as estimateModel;
use app\api\model\MissionSchedule as scheduleModel;
use app\api\model\MissionSign as signModel;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Validate;
use app\ApiController;
use support\Util\InitTree;

use support\Request;

class MissionController extends ApiController
{
    protected $noNeedLogin = ['index', 'getOptions', 'contributeList', 'detail', 'homeCatList', 'comments'];
    protected $noNeedRight = '*';
    
    //错误定义
    private $error_define = [
        1001 => 'Insufficient balance, please recharge',
    ];
    
    /**
     * 任务大厅
     * @return \think\response\Json
     * @throws \\Exception
     */
    public function index()
    {


        $time    = time();
        $request = request();
        $limit   = $request->get('limit', 10);

        $w = $this->getMissionWhere($request);

        //处理排序
        $qsort       = $request->get("sort", 'mission_id');
        $sort_define = [
            'mission_id' => 'mission_id desc',
            'money'      => 'money desc',
            'expire'     => ' (create_time+days_expire*86400-' . $time . ') desc',
            'browse'     => 's.browsed desc',
        ];
        $order = $sort_define[$qsort];
        if (!$order) {
            return $this->error(__("Operation failed"));
        }

        $q = cModel::alias('a')
            ->join("mission_description b", "a.mission_id=b.mission_id")
            ->field("a.*,b.title,b.content,b.req,b.seo")
            ->where($w);

        if ($qsort == 'browse') {
            $q->join("mission_browse s", "a.mission_id=s.mission_id", 'left');
        }

        $q = $q->orderRaw($order);

        $ls = $q->paginate(['list_rows' => $limit, 'request' => $request->all()]);

        $res    = $ls->items();
        $ids    = [];
        $status = cmodel::getStatus();
        $res    = array_map(function ($v) use ($status, &$ids) {
            $v->cat_name   = $this->getLangCatName($v);
            $v->status_txt = $status[$v->status];
            $v->user_info  = $v->user_info;
            $v->profile    = $v->user_info->profile;
            $ids[]         = $v->mission_id;
            $v->route      = createUrl('task', $v->title, $v->mission_id);
            $v->content    = $this->getShortContent($v->content);
            return $v;
        }, $res);

        $stats_schedule = Db::name("mission_schedule")->where("mission_id", 'in', $ids)->field("sum(1) as t,mission_id")->group('mission_id')->select()->toArray();
        if ($stats_schedule) {
            $stats_schedule = array_column($stats_schedule, "t", "mission_id");
        }
        //统计投稿

        $res = array_map(function ($v) use ($stats_schedule, $time) {
            $v['stat_schedule'] = (int) $stats_schedule[$v['mission_id']];
            $v['left_time']     = $v['status'] >= 4 ? "0" . __('minute') : time2Units(($v->getData('create_time') + $v->days_expire * 86400) - $time);
            $v['end_time']      = date("Y-m-d H:i:s", $v->getData('create_time') + $v->days_expire * 86400);
            $v['time_now']      = $time;
            return $v;
        }, $res);

        $data['ls']    = $res;
        $data['total'] = $ls->total();
        $data['lang'] = $this->lang_id;

        return $this->success(__('Operation successful'), $data);

    }


      public function sleep(Request $request)
    {
        sleep(1);
        return response('sleep 1, id:' . $request->input('id'));
    }

    /**
     * 获取查询条件
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    private function getMissionWhere($request)
    {
        $time = time();
        $w[]  = ['a.status', '>', 2];
        $w[]  = ['a.delete_time', '=', 0];

        if ($request->get('mission_no')) {
            $w[] = ['a.mission_no', '=', $request->get('mission_no')];

        }

        if ($request->get('slt_bid_mode')) {
            $w[] = ['a.money_cfg', '<>', ''];
            $w[] = ['a.money_cfg->slt_bid_mode', '=', $request->get('slt_bid_mode')];

        }

        if ($request->get('title')) {
            $w[] = ['b.title', 'like', '%' . $request->get('title') . '%'];

        }
        if ($request->get('content')) {
            $w[] = ['b.content', 'like', '%' . $request->get('content') . '%'];

        }
        if ($request->get('req')) {
            $w[] = ['b.req', 'like', '%' . $request->get('req') . '%'];

        }

        if ($request->get('status')) {
            $w[] = ['a.status', '=', $request->get('status')];

        }

        if ($request->get('seo')) {
            $w[] = ['b.seo->meta_title|b.seo->meta_keyword|b.seo->meta_description', 'like', '%' . $request->get('seo') . '%'];

        }

        if ($request->get('intergralzone')) {
            switch ($request->get('intergralzone')) {
                case 'min':
                    $w[] = ['a.money', '<', 20];
                    break;
                case '1':
                    $w[] = ['a.money', 'between', [20, 50]];
                    break;
                case '2':
                    $w[] = ['a.money', 'between', [50, 100]];
                    break;
                case 'max':
                    $w[] = ['a.money', '>', 100];
                    break;

            }

        }

        if ($request->get('timezone')) {

            switch ($request->get('timezone')) {
                case '1':
                    $w[] = ['a.create_time', '>', ($time - 86400)];
                    break;
                case '3':
                    $w[] = ['a.create_time', '>', ($time - 86400 * 3)];
                    break;
                case '7':
                    $w[] = ['a.create_time', '>', ($time - 86400 * 7)];
                    break;
                case '30':
                    $w[] = ['a.create_time', '>', ($time - 86400 * 30)];
                    break;
                case 'max':
                    $w[] = ['a.create_time', '<=', $time];
                    break;

            }

        }

        if ($request->get('cat_id')) {
            $cat_id = $request->get("cat_id");
            $w[]    = ['a.cat_id', 'in', $this->fetchChildCat($cat_id)];
        }

        return $w;
    }

    /**
     * 获取分类id，构造查询条件
     * @param  [type] $pid [description]
     * @return [type]      [description]
     */
    private function fetchChildCat($pid)
    {

        $tmp = $this->getCats([], 'child', $pid);
        if (is_array($tmp)) {
            $ids_all = implode(',', array_keys($tmp));
        } else {
            $ids_all = $pid;
        }

        return $ids_all;

    }
    /**
     * 多语言环境下分类名称
     * @param  [type] $v [description]
     * @return [type]    [description]
     */
    private function getLangCatName($v)
    {
        if ($v->cat_info) {
            $cats        = $v->cat_info->toArray();
            $cats        = array_column($cats, 'cat_name', 'language_id');
            $v->cat_name = $cats[$this->lang_id];
        } else {
            $v->cat_name = '';
        }
        return $v->cat_name;
    }

    /**
     * 任务详情
     * @return [type] [description]
     */
    public function detail()
    {

        $id   = request()->get("id");
        $data = cModel::with(['attach', 'descriptionShow', 'catInfoShow', 'userInfo.profile', 'catDetail'])->find($id);
        if (!$data) {
            return $this->error(__('Operation failed'));
        }
        //获取器获取
        $data->status_text = $data->status_text;
        

        if ($data->delete_time > 0) {
            return $this->error(__('data_empty'));
        }

        //信用
        $credit = Db::name("user_credit")->where("u_id", $data->userInfo->u_id)->find();
        if (!$credit) {
            $credit['level']    = 1;
            $credit['integral'] = 0;
        }
        $credit['level_txt']    = __(\app\api\model\UserCredit::creditLevel($credit['level'])[0]);
        $data->userInfo->credit = $credit;

        $time              = time();
        
        $data['left_time'] = time2Units($data->getData('create_time') + $data->days_expire * 86400 - $time);
        $data['end_time']  = date('Y-m-d H:i:s', ($data->getData('create_time') + $data->days_expire * 86400));
        //发布任务数
        $data['mission_total'] = (int) cModel::alias("a")->join("mission_description b", "a.mission_id=b.mission_id")->where('a.u_id', $data->u_id)->count();

        //雇主判断
        $data['is_demand'] = $data->u_id == (int) $this->auth->u_id ? 1 : 0;

        $contribute = scheduleModel::where("mission_id", $id)->field("count(1) as `all`,sum(if(status=2,1,0)) as adopt,sum(if(status=3,1,0)) as win")->find();

        $contribute['users'] = signModel::alias('a')->join('user b', 'a.u_id=b.u_id')->join('user_profile p', 'p.u_id=b.u_id', 'left')->join('user_credit ct', 'ct.u_id=b.u_id', 'left')->where("a.mission_id", $id)->field("b.username,b.nickname,b.u_id,p.avatar,ct.level as credit_level,ct.integral as credit_integral")->select()->toArray();

        $contribute['users'] = array_map(function ($v) {
            if (!$v['credit_level']) {
                $v['credit_level']    = 1;
                $v['credit_integral'] = 0;
            }
            $v['credit_level'] && $v['credit_level_txt'] = __(\app\api\model\UserCredit::creditLevel($v['credit_level'])[0]);
            return $v;
        }, $contribute['users']);

        $data['contribute'] = $contribute;
        $browse             = browseModel::where('mission_id', $id)->find();
        $data['browse']     = $browse['browsed'];
        if (!$browse) {
            browseModel::create(['browsed' => 1, 'mission_id' => $id]);

        } else {
            $browse->inc("browsed", 1)->update();
        }
        //判断可报名，可交稿
        $data['sign_able'] = $data['contribute_able'] = $data['current_signed'] = $data['estimate_demand_able'] = 0;
        if ($this->auth->u_id) {
            $signed            = Db::name('mission_sign')->where('mission_id', $id)->where('u_id', $this->auth->u_id)->count();
            $data['sign_able'] = $signed > 0 ? 0 : 1;
            $sign_total        = (int) Db::name('mission_sign')->where('mission_id', $id)->count();
            if ($sign_total >= $data['sign_limit']) {
                $data['sign_able'] = 0;
            }
            $data['current_signed']  = $signed > 0 ? 1 : 0;
            $times                   = $data['money_cfg']['slt_bid_mode'] == 3 ? 3 : 1;
            $has                     = scheduleModel::where('mission_id', $id)->where('u_id', $this->auth->u_id)->count();
            $data['contribute_able'] = 1;
            if ($has >= $times) {
                $data['contribute_able'] = 0;
            }
            $estimate1                    = Db::name("mission_schedule")->where('mission_id', $id)->where('u_id', $this->auth->u_id)->count() > 0;
            $estimate2                    = Db::name("mission_estimate")->where('mission_id', $id)->where('f_uid', $this->auth->u_id)->count() == 0;
            $data['estimate_demand_able'] = $estimate1 && $estimate2 ? 1 : 0;

        }

        return $this->success(__('Operation successful'), $data);
    }

    /**
     * 标记任务完成
     * @return [type] [description]
     */
    public function complete()
    {
        $post = request()->post();
        $id   = $post['id'];

        $info = cModel::find($id);

        if ($this->auth->u_id != $info->u_id) {
            return $this->error(__('Illegal request'));
        }


        Db::startTrans();
        try {
            if ($info->status != 3) {
                throw new \Exception(__('Only tasks in progress can be marked'));
            }
            $stat_success = Db::name('mission_schedule')->where('mission_id', $id)->where("status", 3)->count();
            if ($stat_success == 0) {
                throw new \Exception(__('manuscript_need'));
            }
            $info->save(['status' => 4]);

            $r = $this->dealCompleteMoney($info);
            //增加信用分
            $total              = $r['total'];
            $money_actual       = $r['money_actual'];
            $rate               = round(($total - $money_actual) * 100 / $total);
            $credit_type_prefix = time() > ($info->getData('create_time') + $info->days_expire * 86400) ? 'complete_mission_exp_' : 'complete_mission_';

            if ($rate < 20) {
                $credit_type = $credit_type_prefix . 'l20';

            } elseif ($rate < 50) {
                $credit_type = $credit_type_prefix . 'l50';

            } elseif ($rate >= 50) {
                $credit_type = $credit_type_prefix . 'm50';
            }
           
            //信用分
            Credit::sceneLog($this->auth->u_id, $credit_type, ['uk' => $info->mission_id]);
            //信用分当月
            $month_data = monthBeginAndEnd();
            if (date("Y-m-d") == date("Y-m-d", $month_data[1])) {
                $w               = [];
                $w[]             = ['u_id', '=', $this->auth->u_id];
                $w[]             = ['create_time', 'between', implode(',', $month_data)];
                $month_t         = Db::name('mission')->where($w)->count();
                 
                $w[]             = ['status', '>', 3];
                $month_t_fininsh = Db::name('mission')->where($w)->count();                
                $rate            = $month_t_fininsh * 100 / $month_t;     
 
  

                if ($rate > 99) {
                    Credit::sceneLog($this->auth->u_id,'complete_pct100',['uk' => date('Y-m')]);
                } elseif ($rate > 49) {   

                    Credit::sceneLog($this->auth->u_id,'complete_pct50', ['uk' => date('Y-m')]);
                }
               
            }
            Db::commit();
         
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success(__('Operation successful'),[]);
    }

    /**
     * 完成时款项处理
     * @param  [type] $info [description]
     * @return [type]       [description]
     */
    private function dealCompleteMoney($info)
    {
        $money_actual = 0;
        $total        = $info->money;
        $cfg          = $info->money_cfg;
        $prize_mode   = $cfg['slt_bid_mode'];

        $has;
        if ($prize_mode == 1) {
            $has[1] = [1, $total];
        } elseif ($prize_mode == 2) {
            $has[1] = [(int) $cfg['txt_pople_1'], (int) $cfg['txt_avg_money_1']];
            $has[2] = [(int) $cfg['txt_pople_2'], (int) $cfg['txt_avg_money_2']];
            $has[3] = [(int) $cfg['txt_pople_3'], (int) $cfg['txt_avg_money_3']];
        } elseif ($prize_mode == 3) {
            $has[1] = [(int) $cfg['gj_num'], (int) $cfg['gj_money']];
        }
        $moneys = [];

        if ($info->contributes && !$info->contributes->isEmpty()) {

            $contributes = $info->contributes->toArray();

            $data = [];

            foreach ((array) $contributes as $v) {
                if ($v['status'] != 3) {
                    continue;
                }
                $level = (int) $v['prize_level'] > 0 ? $v['prize_level'] : 1;

                if ($data[$level] < $has[$level][0]) {

                    $data[$level]++;
                    $v['money'] = $has[$level][1];
                    $moneys[]   = ['u_id' => $v['u_id'], 'plus' => $v['money'], 'op_type' => 4, 'op_key' => $v['id']];
                }

            }

            //实际任务金额
            $money_actual = array_sum(array_column($moneys, 'plus'));
            $info->save(['money_actual' => $money_actual]);
            if ($money_actual < $total) {
                $this->refundPartForMission($total - $money_actual, $info);
            }

            $this->updateScheduleMoney($total, $moneys);
        } else {

            throw new \Exception(__("Please rate the qualified manuscripts"));

        }

        return ['total' => $total, 'money_actual' => $money_actual];

    }

    /**
     * 部分退款处理
     * @param  [type] $money [description]
     * @param  [type] $info  [description]
     * @return [type]        [description]
     */
    public function refundPartForMission($money, $info)
    {
        if ($money <= 0) {
            return;
        }
        //退还款项
        $time  = time();
        $total = $money;

        $before = Db::name("user")->where('u_id', $info->u_id)->lock(true)->value('money');

        $data = [
            'u_id'        => $info->u_id,
            'plus'        => $total,
            'before'      => $before,
            'after'       => $before + $total,
            'memo'        => __('Task partial refund'),
            'create_time' => $time,
            'update_time' => $time,
            'op_type'     => 5,
            'op_key'      => $info->mission_id,
        ];
        $validate = new \app\admin\validate\MoneyLog;
        $result   = $validate->check($data);
        if (!$result) {
            throw new \Exception(__('There is a problem with the parameter'));
        }

        Db::name("user_money_log")->insert($data);
        Db::name("user")->where('u_id', $info->u_id)->inc('money', $total)->update();
    }

    /**
     * 更新稿件款项
     * @param  [type] $moneys [description]
     * @return [type]         [description]
     */
    private function updateScheduleMoney($total, $moneys)
    {

        if (array_sum(array_column($moneys, 'plus')) > $total) {
            throw new \Exception(__("The total amount of manuscript payment exceeds the task reward amount"), 1);
        }
        $time = time();
        foreach ($moneys as $key => $value) {
            $before = Db::name('user')->where('u_id', $value['u_id'])->lock(true)->value('money');
            Db::name('user_money_log')->insert([
                'u_id'        => $value['u_id'],
                'plus'        => $value['plus'],
                'before'      => $before,
                'after'       => $before + $value['plus'],
                'op_type'     => $value['op_type'],
                'op_key'      => $value['op_key'],
                'create_time' => $time,
                'update_time' => $time,
            ]);
            Db::name('mission_schedule')->where('id', $value['op_key'])->update(['money' => $value['plus'], 'update_time' => $time]);
            Db::name('user')->where('u_id', $value['u_id'])->inc('money', $value['plus'])->update();
        }

        return true;

    }

    /**
     * 创建任务
     * @return [type] [description]
     */
    public function create()
    {
        try {
            $post         = request()->post();
            $post['u_id'] = $this->auth->u_id;
            $validate     = new \app\api\validate\Mission;
            $result       = $validate->check($post);
            if (!$result) {
                return $this->error($validate->getError());
            } else {
                Db::startTrans();
                $cmodel = new cModel;
                //默认不付款
                $post['status'] = 1;

                $seo = $this->fetchSeo($post);

                $description = [
                    'language_id' => $this->lang_id,
                    'title'       => $post['title'],
                    'content'     => $this->request->post('content', '', 'htmlspecialchars'),
                    'seo'         => $seo,
                ];
                $post['mission_no'] = get_order_sn();

                $data = $cmodel->together(['description' => $description])->save($post);
                if (!$data) {
                    throw new \Exception(__('Operation failed'));
                }
                if ($cmodel->money <= 0) {
                    throw new \Exception(__('Operation failed'));
                }

                $payed = $this->payForMission($cmodel->mission_id, $cmodel->money);
              
                $payed && $cmodel->where('mission_id',$cmodel->misson_id)->save(['status' => 2]);

                $r = $cmodel->find($cmodel->mission_id);
                if (!$this->checkMoneyCfg($r->money_cfg)) {
                    throw new \Exception(__('Invalid parameter'));
                }
                //增加信用分
                Credit::sceneLog($post['u_id'], 'mission_create');
                $total = $cmodel->where("u_id", $this->auth->u_id)->count();
                if ($total > 10) {
                    Credit::sceneLog($post['u_id'], 'mission_pub10');
                }
                if ($total > 11 && $total % 10 == 0) {
                    Credit::sceneLog($post['u_id'], 'mission_double10', ['uk' => $total / 10]);
                }

                Db::commit();
                return $this->success(__('Operation successful'), ['payed' => $payed, 'mission_id' => $cmodel->mission_id]);

            }
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }

    }

    /**
     * 更新任务
     * @return [type] [description]
     */
    public function update()
    {
        Db::startTrans();
        try {
            $post     = request()->post();
            $validate = new \app\api\validate\Mission;
            $result   = $validate->scene('edit')->check($post);
            if (!$result) {
                return $this->error($validate->getError());
            } else {

                $info = cModel::find($post['mission_id']);
                if (!$info) {
                    throw new \Exception(__("Operation failed"));
                }
                if ($info->u_id != $this->auth->u_id) {
                    throw new \Exception(__("Illegal request"));
                }
                if ($info->status > 1) {
                    throw new \Exception(__("after payed cannot be edited"));
                }
                $description = [
                    'language_id' => $this->lang_id,
                    'title'       => $post['title'],
                    'content'     => $this->request->post('content', '', 'htmlspecialchars'),
                ];
                $data = $info->together(['description' => $description])->save($post);
                $info = cModel::find($post['mission_id']);
                if (!$this->checkMoneyCfg($info->money_cfg)) {
                    throw new \Exception(__('Invalid parameters'));
                }

                if (!$data) {
                    throw new \Exception(__('Operation failed'));
                }
                Db::commit();
                return $this->success(__('Operation successful'), ['mission_id' => $info->mission_id]);

            }
        } catch (\Exception $e) {

            return $this->error($e->getMessage());
        }

    }

    /**
     * 检查金币配置数据合法性
     * @return [type] [description]
     */
    private function checkMoneyCfg($data)
    {
        if (!is_array($data)) {
            return false;
        }
        if (!$data['slt_bid_mode']) {
            return false;
        }
        return true;
    }

    /**
     * 任务删除
     * @return [type] [description]
     */
    public function delete()
    {
        $id = $this->request->get("mission_id");
        if (!$id) {
            return $this->error(__('Invalid parameters'));
        }
        Db::startTrans();
        try {

            $info = cModel::where('status', '<', '3')->where('mission_id', $id)->find();
            if (!$info) {
                throw new \Exception(__("Operation failed"), 1);
            }
            if ($info->u_id != $this->auth->u_id) {
                throw new \Exception(__("Illegal request"), 1);

            }
            //款项处理
            if ($info->status == 2) {
                $this->refundForDel($info);
            }
            $info->delete();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success(__('Operation successful'));
    }

    /**
     * 任务付款接口
     * @return [type] [description]
     */
    public function missoinPay()
    {
        $error_no = 0;
        try {
            $mission_id = $this->request->get("mission_id");
            $model      = cModel::find($mission_id);
            if (!$model) {
                throw new \Exception(__('Operation failed'), 1);

            }

            if ($model->u_id != $this->auth->u_id) {
                throw new \Exception(__('Operation failed'), 1);
            }

            if ($model->status > 1) {

                throw new \Exception(__('Task paid'), 1);
            }

            $payed = $this->payForMission($mission_id, $model->money);
            if ($payed) {
                $model->save(['status' => 2]);
                return $this->success(__('Operation successful'));
            } else {
                $error_no = "1001";
                throw new \Exception(__($this->error_define[$error_no]), 1);
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), ['error_no' => $error_no]);
        }
    }

    /**
     * 删除退款处理
     * @return [type] [description]
     */
    private function refundForDel($info)
    {
        $total = Db::name("user_money_log")->where('u_id', $info->u_id)->where('op_type', 3)->where('op_key', $info->mission_id)->value('reduce');
        if (!$total) {
            throw new \Exception(__('Task payment record missing'));
        }

        //退还款项
        $time = time();

        $before = Db::name("user")->where('u_id', $info->u_id)->lock(true)->value('money');

        $data = [
            'u_id'        => $info->u_id,
            'plus'        => $total,
            'before'      => $before,
            'after'       => $before + $total,
            'memo'        => __('Task delete refund'),
            'create_time' => $time,
            'update_time' => $time,
            'op_type'     => 5,
            'op_key'      => $info->mission_id,
        ];
        $validate = new \app\admin\validate\MoneyLog;
        $result   = $validate->check($data);
        if (!$result) {
            throw new Validate\Exception(__('There is a problem with the parameter'));
        }

        Db::name("user_money_log")->insert($data);
        Db::name("user")->where('u_id', $info->u_id)->inc('money', $total)->update();
    }

    /**
     * 辅助扣除悬赏付款
     * @return [type] [description]
     */
    private function payForMission($mission_id, $mission_money)
    {
        $balance = \app\api\model\User::where('u_id', $this->auth->u_id)->lock(true)->find();
        $left    = $balance->money - $balance->freeze;
        $payed   = 0;
        if ($left >= $mission_money) {
            $balance->dec('money', $mission_money)->update();
            \app\api\model\UserMoneyLog::create([
                'u_id'    => $this->auth->u_id,
                'reduce'  => $mission_money,
                'before'  => $balance->money,
                'after'   => $balance->money - $mission_money,
                'op_type' => 3,
                'op_key'  => $mission_id,
            ]
            );
            $payed = 1;
        }
        return $payed;
    }

    /**
     * 任务报名
     * @return [type] [description]
     */
    public function sign()
    {
        try {
            $post         = request()->post();
            $post['u_id'] = $this->auth->u_id;
            $validate     = new \app\api\validate\MissionSign;
            $result       = $validate->check($post);
            if (!$result) {
                return $this->error($validate->getError());
            } else {
                $model = new signModel;
                $info  = cModel::where('mission_id', $post['mission_id'])->find();
                $ct    = $model->where('mission_id', $post['mission_id'])->count();
                if ($info->status != 3) {
                    throw new \Exception(__("Only tasks in progress can be sign up"), 1);

                }

                if (($info->getData('create_time') + $info->days_expire * 86400) < time()) {
                    throw new \Exception(__("The task has expired"), 1);
                }

                if ($info->sign_limit > 0 && $ct >= $info->sign_limit) {
                    throw new \Exception(__("The number of applicants exceeds the limit"), 1);
                }
                if ($model->where('mission_id', $post['mission_id'])->where('u_id', $this->auth->u_id)->count()) {
                    throw new \Exception(__("You have signed up"), 1);

                }
                $data = $model->save($post);

                //增加信用分
                Credit::sceneLog($this->auth->u_id, 'mission_sign', ['uk' => $post['mission_id']]);

                //信用分当月
                $month_data = monthBeginAndEnd();
                $w          = [];
                $w[]        = ['u_id', '=', $this->auth->u_id];
                $w[]        = ['create_time', 'between', implode(',', $month_data)];
                $t          = Db::name('mission_sign')->where($w)->count();
                if ($t > 10) {
                    Credit::sceneLog($this->auth->u_id, 'mission_sign10', ['uk' => date('Y-m')]);
                }

                if (!$data) {
                    return $this->error(__('Operation failed'));
                } else {
                    return $this->success(__('Operation successful'), $data);
                }
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }

    }

    /**
     * 稿件提交
     * @return [type] [description]
     */
    public function contributeSubmit()
    {
        try {
            $mission_id = request()->post('mission_id');
            if (!$mission_id) {
                throw new \Exception(__("Invalid parameters"), 1);
            }
            $mission_info = cModel::find($mission_id);
            if (!$mission_info->status > 3) {
                throw new \Exception(__("Task closed"), 1);
            }

            if (!$mission_info->money_cfg) {
                throw new \Exception(__("Invalid parameters"), 1);
            }
            if (($mission_info->getData('create_time') + $mission_info->days_expire * 86400) < time()) {
                throw new \Exception(__("The task has expired"), 1);
            }

            $sign_info = signModel::where('mission_id', $mission_id)->where('u_id', $this->auth->u_id)->find();
            if (!$sign_info) {
                throw new \Exception(__("Please sign first"), 1);
            }
            //个人投稿最多3次
            $times = $mission_info->money_cfg['slt_bid_mode'] == 1 ? 1 : 3;
            $has   = scheduleModel::where('mission_id', $mission_id)->where('u_id', $this->auth->u_id)->count();
            if ($has >= $times) {
                throw new \Exception(sprintf(__("According to the configuration, you can only participate %s times"), $times), 1);
            }
            $post         = request()->post();
            $post['u_id'] = $this->auth->u_id;
            $validate     = new \app\api\validate\MissionSchedule;
            $result       = $validate->check($post);
            if (!$result) {
                return $this->error($validate->getError());
            } else {
                $model           = new scheduleModel;
                $post['content'] = $this->request->post('content', '', 'htmlspecialchars');
                $data            = $model->save($post);
                if (!$data) {
                    return $this->error(__('Operation failed'));
                } else {
                    return $this->success(__('Operation successful'), $data);
                }
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 稿件列表
     * @return [type] [description]
     */
    public function contributeList()
    {

        $model      = new \app\api\model\MissionSchedule;
        $request    = request();
        $mission_id = $request->get("mission_id");
        $limit      = $request->get('limit', 10);
        $w[]        = ['a.mission_id', '=', $mission_id];

        if ($request->get('content')) {
            $w[] = ['a.content', 'like', '%' . $request->get('content') . '%'];

        }

        if ($request->get('status')) {
            $w[] = ['a.status', '=', $request->get('status')];

        }

        $q = $model::alias('a')
            ->with(['attach'])
            ->join("mission b", "a.mission_id=b.mission_id ", 'left')
            ->field("a.*")
            ->where($w);

        $ls = $q->paginate(['list_rows' => $limit, 'request' => $request->all()]);

        $res     = $ls->items();
        $ids     = [];
        $status  = $model::getStatus();
        $cur_uid = $this->auth->u_id;

        $uids  = array_column($ls->items(), 'u_id');
        $stars = Db::name("mission_estimate")->where('mission_id', $mission_id)->column('score', 't_uid');

        $res = array_map(function ($v) use ($status, &$ids, $cur_uid, $stars) {
            $v->star_level = (int) $stars[$v->u_id];
            $v->status_txt = $status[$v->status];
            $v->user_info  = $this->fullUserInfo($v->user_info);
            $v->profile    = $v->user_info->profile;
            $v->attach     = $v->user_info->profile;
            $tmp_content   = trim(html2text(htmlspecialchars_decode($v->content)));
            if ($v->u_id != $cur_uid && $v->status < 2) {
                $v->content = $v->view_able < 100 ? msubstr($tmp_content, 0, ceil($v->view_able / 100 * mb_strlen($tmp_content))) : $tmp_content;
            } else {
                $v->content = htmlspecialchars_decode($v->content);
            }
            return $v;
        }, $res);

        $data['ls'] = $res;

        $data['total'] = $ls->total();

        return $this->success(__('Operation successful'), $data);
    }

    /**
     * 稿件详情
     * @return [type] [description]
     */
    public function contributeDetail()
    {
        $id         = request()->get("id");
        $model      = new \app\api\model\MissionSchedule;
        $data       = $model->with(['userInfo', 'attach'])->find($id);
        $demand_uid = cModel::where('mission_id', $data->mission_id)->value('u_id');
        if ($data->u_id != $this->auth->u_id && $data->status < 2) {
            $tmp_content   = trim(strip_tags(htmlspecialchars_decode($data->content)));
            $data->content = $data->view_able ? substr($tmp_content, 0, ceil($data->view_able * strlen($tmp_content) / 100)) : htmlspecialchars_decode($data->content);
        }
        $data->user_info = $this->fullUserInfo($data->user_info);
        return $this->success(__('Operation successful'), $data);
    }

    /**
     * 我创建的任务
     * @param  [type] $token [登录token]
     * @return [type]        [json数据]
     */
    public function myCreated($token)
    {

        $request = request();
        $limit   = $request->get('limit', 10);
        $w[]     = ['a.u_id', '=', $this->auth->u_id];
        $w[]     = ['a.delete_time', '=', 0];
        if ($request->get('title')) {
            $w[] = ['b.title', 'like', '%' . $request->get('title') . '%'];

        }
        if ($request->get('content')) {
            $w[] = ['b.content', 'like', '%' . $request->get('content') . '%'];

        }

        if ($request->get('status')) {
            $w[] = ['a.status', '=', $request->get('status')];

        }

        if ($request->get('seo')) {
            $w[] = ['b.seo->meta_title|b.seo->meta_keyword|b.seo->meta_description', 'like', '%' . $request->get('seo') . '%'];

        }

        $q = cModel::alias('a')
            ->join("mission_description b", "a.mission_id=b.mission_id")
            ->field("a.*,b.title,b.content,b.req,b.seo")
            ->where($w);
        if ($request->get('cat_id')) {
            $q->where('a.cat_id', $request->get("cat_id"));
        }
        $q->order("a.mission_id desc");

        $ls = $q->paginate(['list_rows' => $limit, 'request' => $request->all()]);

        $res = $ls->items();
        $ids = [];
        $res = array_map(function ($v) use ($status, &$ids) {
            $v->cat_name   = $this->getLangCatName($v);
            $v->status_txt = $status[$v->status];
            $v->user_info  = $v->user_info;
            $v->profile    = $v->user_info->profile;
            $ids[]         = $v->mission_id;
            $v->content    = $this->getShortContent($v->content);
            $v->route      = createUrl('task', $v->title, $v->mission_id);
            return $v;
        }, $res);

        $data['ls']    = $res;
        $data['total'] = $ls->total();

        return $this->success(__('Operation successful'), $data);

    }

    /**
     * 我参与的任务
     * @param  [type] $token [登录token]
     * @return [type]        [json数据]
     */
    public function myInvolved($token)
    {

        $request = request();
        $limit   = $request->get('limit', 10);
        $w[]     = ['s.u_id', '=', $this->auth->u_id];
        $w[]     = ['m.status', '>', 2];
        $w[]     = ['m.delete_time', '=', 0];
        if ($request->get('title')) {
            $w[] = ['b.title', 'like', '%' . $request->get('title') . '%'];

        }
        if ($request->get('content')) {
            $w[] = ['b.content', 'like', '%' . $request->get('content') . '%'];

        }
        if ($request->get('req')) {
            $w[] = ['b.req', 'like', '%' . $request->get('req') . '%'];

        }

        if ($request->get('status')) {
            $w[] = ['m.status', '=', $request->get('status')];

        }

        if ($request->get('time_s')) {
            $w[] = ['m.create_time', '>=', strtotime($request->get('time_s') . ' 00:00:00')];

        }

        if ($request->get('time_e')) {
            $w[] = ['m.create_time', '<=', strtotime($request->get('time_e') . " 23:59:59")];

        }

        if ($request->get('seo')) {
            $w[] = ['b.seo->meta_title|b.seo->meta_keyword|b.seo->meta_description', 'like', '%' . $request->get('seo') . '%'];

        }

        $q = cModel::alias('m')
            ->join("mission_sign s", "s.mission_id=m.mission_id")
            ->join("mission_description b", "m.mission_id=b.mission_id ")
            ->field("m.*,b.title,b.content,b.req,b.seo,m.status as mission_status,s.create_time as invoce_time")
            ->where($w);

        if ($request->get('cat_id')) {
            $q->where('a.cat_id', $request->get("cat_id"));
        }

        $q->order("s.id desc");
        $ls  = $q->paginate(['list_rows' => $limit, 'request' => $request->all()]);
        $res = $ls->items();

        $ids = [];
        $res = array_map(function ($v) use ($status, &$ids) {
            $v->cat_name    = $this->getLangCatName($v);
            $v->status_txt  = $status[$v->status];
            $v->user_info   = $v->user_info;
            $v->profile     = $v->user_info->profile;
            $ids[]          = $v->mission_id;
            $v->dissent     = $v->dissent;
            $v->invoce_time = date("Y-m-d H:i:s");
            if ($v->dissent) {
                $v->dissent->status_text = $v->dissent->status_text;
            }
            $v->route = createUrl('task', $v->title, $v->mission_id);
            return $v;
        }, $res);

        $data['ls'] = $res;

        $data['total'] = $ls->total();
        return $this->success(__('Operation successful'), $data);

    }

    /**
     * 我成功的案列
     * @param  [type] $token [登录token]
     * @return [type]        [json数据]
     */
    public function mySuccess($token)
    {

        $request = request();
        $limit   = $request->get('limit', 10);
        $w[]     = ['s.u_id', '=', $this->auth->u_id];
        $w[]     = ['m.status', '>=', 4];
        $w[]     = ['m.delete_time', '=', 0];
        if ($request->get('title')) {
            $w[] = ['b.title', 'like', '%' . $request->get('title') . '%'];

        }
        if ($request->get('content')) {
            $w[] = ['b.content', 'like', '%' . $request->get('content') . '%'];

        }
        if ($request->get('req')) {
            $w[] = ['b.req', 'like', '%' . $request->get('req') . '%'];

        }

        if ($request->get('status')) {
            $w[] = ['m.status', '=', $request->get('status')];

        }

        if ($request->get('time_s')) {
            $w[] = ['m.create_time', '>=', strtotime($request->get('time_s') . ' 00:00:00')];

        }

        if ($request->get('time_e')) {
            $w[] = ['m.create_time', '<=', strtotime($request->get('time_e') . " 23:59:59")];

        }

        if ($request->get('seo')) {
            $w[] = ['b.seo->meta_title|b.seo->meta_keyword|b.seo->meta_description', 'like', '%' . $request->get('seo') . '%'];

        }

        $q = cModel::alias('m')
            ->join("mission_schedule s", "s.mission_id=m.mission_id and s.status=3")
            ->join("mission_description b", "m.mission_id=b.mission_id")
            ->field("m.*,b.title,b.content,b.req,b.seo,m.status as mission_status,s.create_time as invoce_time")
            ->where($w);

        if ($request->get('cat_id')) {
            $q->where('a.cat_id', $request->get("cat_id"));
        }

        $q->order("s.id desc");

        $ls = $q->paginate(['list_rows' => $limit, 'request' => $request->all()]);

        $res = $ls->items();

        $ids = [];
        $res = array_map(function ($v) use ($status, &$ids) {
            $v->cat_name    = $this->getLangCatName($v);
            $v->status_txt  = $status[$v->status];
            $v->user_info   = $v->user_info;
            $v->profile     = $v->user_info->profile;
            $ids[]          = $v->mission_id;
            $v->dissent     = $v->dissent;
            $v->invoce_time = date("Y-m-d H:i:s");
            $v->route       = createUrl('task', $v->title, $v->mission_id);
            if ($v->dissent) {
                $v->dissent->status_text = $v->dissent->status_text;
            }
            return $v;
        }, $res);

        $data['ls'] = $res;

        $data['total'] = $ls->total();
        return $this->success(__('Operation successful'), $data);

    }

    /**
     * 我的稿件列表
     * @return [type] [description]
     */
    public function myContributeList()
    {
        $model      = new \app\api\model\MissionSchedule;
        $request    = request();
        $mission_id = $request->get("mission_id");
        $info       = cModel::find($mission_id);
        if (!$info) {
            return $this->error(__('Operation failed'));
        }
        if ($info->u_id != $this->auth->u_id) {
            return $this->error(__('Illegal request'));
        }
        $limit = $request->get('limit', 10);
        $w[]   = ['a.mission_id', '=', $mission_id];

        if ($request->get('content')) {
            $w[] = ['a.content', 'like', '%' . $request->get('content') . '%'];

        }

        if ($request->get('status')) {
            $w[] = ['a.status', '=', $request->get('status')];

        }

        $q = $model::alias('a')
            ->join("mission b", "a.mission_id=b.mission_id ", 'left')
            ->field("a.*")
            ->where($w);

        $ls = $q->paginate(['list_rows' => $limit, 'request' => $request->all()]);

        $res    = $ls->items();
        $ids    = [];
        $status = $model::getStatus();
        $res    = array_map(function ($v) use ($status, &$ids) {
            $v->status_txt = $status[$v->status];
            $v->user_info  = $v->user_info;
            $v->profile    = $v->user_info->profile;
            $v->content    = $this->getShortContent($v->content);
            return $v;
        }, $res);

        $data['ls']    = $res;
        $data['total'] = $ls->total();

        return $this->success(__('Operation successful'), $data);
    }

    /**
     * 申请仲裁
     * @return [type] [description]
     */
    public function arbitration()
    {
        $post = $this->request->post();
        $f    = \app\api\model\MissionSchedule::where([
            ['u_id', '=', $this->auth->u_id],
            ['mission_id', '=', $post['mission_id']],
            ['status', '>', 1],
        ])->find();
        if (!$f) {
            return $this->error(__('Your manuscript has not been accepted and arbitration cannot be initiated'));
        } elseif (\app\api\model\MissionDissent::where([['u_id', '=', $this->auth->u_id], ['mission_id', '=', $post['mission_id']]])->find()) {
            return $this->error(__('Arbitration has been applied, and each person can only initiate it once'));
        } else {
            $data = \app\api\model\MissionDissent::create([
                'mission_id' => $post['mission_id'],
                'u_id'       => $this->auth->u_id,
                'content'    => $post['content'],
            ]
            );
            return $this->success(__('Operation successful'), $data);
        }
    }

    /**
     * 采纳稿件
     * @return [type] [description]
     */
    public function adopt()
    {
        $post = request()->post();
        $id   = $post['id'];

        $info = \app\api\model\MissionSchedule::find($id);
        if (!$info) {
            return $this->error(__('Operation failed'));
        }
        if ($info->status > 1) {
            return $this->error(__('It has been adopted'));
        }
        $mission_id = $info['mission_id'];

        $f = Db::name('mission')->where('mission_id', $mission_id)->find();

        if ($this->auth->u_id != $f['u_id']) {
            return $this->error(__('Illegal request'));
        }

        if ($f['status'] > 3) {
            return $this->error(__('Operation failed'));
        }

        $data = $info->save(['status' => 2]);
        //增加信用分
        Credit::sceneLog($info->u_id, 'manuscript_accept', ['uk' => $id]);
        return $this->success(__('Operation successful'), $data);
    }

    /**
     * 标记稿件合格
     * @return [type] [description]
     */
    public function markqualified()
    {
        $post = request()->post();
        $id   = $post['id'];

        $info = \app\api\model\MissionSchedule::find($id);

        if ($info->status == "3") {
            return $this->error(__('It has been marked'));
        }

        if ($info->status < 2) {
            return $this->error(__('must adopted first'));
        }

        $mission_id = $info->mission_id;

        $info_mission = cModel::find($mission_id);

        if ($this->auth->u_id != $info_mission->u_id) {
            return $this->error(__('Illegal request'));
        }

        if ($info_mission->status > 3) {
            return $this->error(__('Operation failed'));
        }

        $cfg        = $info_mission->money_cfg;
        $prize_mode = $cfg['slt_bid_mode'];

        $has;

        $prize_level = (int) $this->request->post('prize_level');
        if ($prize_mode == 1) {
            $has[$prize_mode][0] = 1;
        } elseif ($prize_mode == 2) {
            $has[$prize_mode][1] = (int) $cfg['txt_pople_1'];
            $has[$prize_mode][2] = (int) $cfg['txt_pople_2'];
            $has[$prize_mode][3] = (int) $cfg['txt_pople_3'];
        } elseif ($prize_mode == 3) {
            $has[$prize_mode][0] = (int) $cfg['gj_num'];
        }

        $ct = \app\api\model\MissionSchedule::where('mission_id', $mission_id)->where('status', 3)->where('prize_level', $prize_level)->count();
        if ($ct >= $has[$prize_mode][$prize_level]) {
            return $this->error(__("Qualified parts exceed task configuration"), 1);
        }

        $data = $info->save(['status' => 3, 'prize_level' => $prize_level]);
        //增加信用分
        Credit::sceneLog($info->u_id, 'manuscript_qualified', ['uk' => $id]);
        return $this->success(__('Operation successful'), $data);
    }

    /**
     * 获取选项或者辅助参数
     * @return [type] [description]
     */
    public function getOptions()
    {
       
        $params = request()->post('params');
        $params = explode(',', $params);
        foreach ($params as $key => $value) {
            if ($value == 'mission_category') {
                $options[$value] = $this->getCats([], 'child');
            }

            if ($value == 'category_list') {
                $options[$value] = $this->getCats([], 'list');
            }
            if ($value == 'mission_status') {
                $options[$value] = cModel::getStatus();
            }

            if ($value == 'mission_hall_status') {
                $options[$value] = cModel::getHallStatus();
            }

            if ($value == 'timezone') {
                $options[$value] = $this->getDateZone();
            }

            if ($value == 'intergralzone') {
                $options[$value] = $this->getIntegralZone();
            }

            if ($value == 'mission_config') {
                $options[$value] = $this->getMissionConfig();
            }
            if ($value == 'money_type') {
                $options[$value] = \app\api\model\UserMoneyLog::getOpType();
            }

            if ($value == 'langset') {
               
               
                $options[$value] = ['langs' => getLangs(), 'current' =>'zh_CN'];
            }

            if ($value == 'mission_category_stat') {
                $ids = $this->request->post('cat_ids');
                $ids = explode(",", $ids);
                foreach ($ids as $key => $item) {
                    $options[$value][$item] = $this->getMissionCatStat($item);
                }

            }

            if($value=='creditTypes'){
                $options[$value] = \app\api\model\UserCredit::creditBasic();
            }

        }
       
        $data = $options;
        return $this->success(__('Operation successful'), $data);
    }

    /**
     * 分类任务统计接口，包含稿件数，任务数，任务金额
     * @return [type] [description]
     */

    private function getMissionCatStat($pid)
    {

        $ids_all = $this->fetchChildCat($pid);
        $ids_all = explode(',', $ids_all);

        foreach ((array) $ids_all as $v) {

            $contributes = Db::name('mission_schedule')->alias("s")->join('mission m', 's.mission_id=m.mission_id')->join("mission_description d", "d.mission_id=m.mission_id")->where('m.cat_id', 'in', $v)->count();

            $mission = Db::name('mission')->alias('m')->join("mission_description d", "d.mission_id=m.mission_id")->where('m.cat_id', 'in', $v)->field('sum(1) as t_num,sum(m.money) as t_money')->find();

            $stat[$v] = [
                'contibute'     => (int) $contibutes,
                'mission_num'   => (int) $mission['t_num'],
                'mission_money' => (int) $mission['t_money'],
                'avg_money'     => (int) ceil($contibutes ? $mission['t_money'] / $contibutes : 0),
            ];
        }

        return $stat;
    }

    /**
     * 任务配置
     * @return [type] [description]
     */
    private function getMissionConfig()
    {
        $cfg = getConfig("mission");
        return $cfg;
    }

    /**
     * 搜索时间区间
     * @return [type] [description]
     */
    private function getDateZone()
    {
        return [
            '1'   => __('24 hours'),
            '3'   => __('3 days'),
            '7'   => __('7 days'),
            '30'  => __('30 days'),
            'max' => __('max days'),
        ];
    }

    /**
     * 搜索积分区间
     * @return [type] [description]
     */
    private function getIntegralZone()
    {
        return [
            'min' => __('Below 20 points'),
            '1'   => __('20-50 points'),
            '2'   => __('50-100 points'),
            'max' => __('More than 100 points'),
        ];
    }

    /**
     * 生成分类select列表
     * @param  [type] $sel [选中项]
     * @return [type]      [数组]
     */
    private function getCats($sel, $type = 'select', $pid = 0)
    {

        $menus = Db::name('cat')->alias('a')->join("cat_description b", 'a.cat_id=b.cat_id and b.language_id=' . $this->lang_id, 'left')->where('a.group', '任务')->column("a.cat_id as id,b.cat_name as name,a.pid as parentid,a.sorted as `order`", "a.cat_id");

        $tree = new InitTree;
        $tree->set_tree($menus);
        if ($type == 'select') {

            $cat_options = $tree->get_tree_multi($pid, "<option value=\$id \$selected>\$spacer\$name</option>", $sel);
        } elseif ($type == 'child') {
            $cats = $tree->listToTree($pid);
            foreach ($cats as $key => $value) {
                $cat_options[$value['id']] = $value;
            }
        } elseif ($type == 'list') {
            $cat_options = $menus;
        } else {
            $cat_options = $tree->get_childs($pid);
        }

        return $cat_options;

    }

    /**
     * 词汇
     * @param  [type] $text [description]
     * @return [type]       [description]
     */
    public function fetchSeo($post)
    {
        require_once base_path() . '/extend/scw4/pscws4.class.php';
        $cws = new \PSCWS4('utf8');
        $cws->set_dict(base_path() . '/extend/scw4/etc/dict.utf8.xdb');
        $cws->set_rule(base_path() . '/extend/scw4/etc/rules.utf8.ini');
        $cws->send_text($post['title']);
        $ret     = $cws->get_tops(10, 'r,v,p');
        $keyword = implode(',', array_column($ret, 'word'));
        $r       = [
            'meta_title'       => $post['title'],
            'meta_keyword'     => $keyword,
            'meta_description' => $this->getShortContent($post['content'], 20, ''),
        ];

        return $r;
    }

    /**
     * 首页分类数据调用
     * @return [type] [description]
     */
    public function homeCatList()
    {
        $pid   = $this->request->get("pid");
        $limit = $this->request->get("limit");
        $limit = $limit > 15 ? 15 : $limit;
        if (!$pid) {
            return $this->error(__('Invalid parameters'));
        } else {
            $pids = explode(',', $pid);
            $alls = [];
            foreach ($pids as $item) {
                $main                = \app\api\model\Cat::with("description")->find($item);
                $alls[$item]['main'] = $main;
                $cats                = Db::name('cat')->alias('a')
                    ->join("cat_description b", 'a.cat_id=b.cat_id and b.language_id=' . $this->lang_id, 'left')->where('a.pid', $item)->column("a.cat_id,b.cat_name,a.pid ,a.sorted ", "a.cat_id");
                $ids_cat = array_keys($cats);
                foreach ($ids_cat as $key => $v) {
                    $ls = cModel::alias("a")->join('mission_description b', "a.mission_id=b.mission_id")->where("a.cat_id", $v)->field('a.mission_id,a.cat_id,a.money,b.title,b.content,b.req')->limit($limit)->select();

                    foreach ($ls as $kt => $vt) {
                        $vt->route = createUrl('task', $vt->title, $vt->mission_id);
                        $ls[$kt]   = $vt;
                    }

                    $cats[$v]['missions'] = $ls;

                    $alls[$item]['_child'] = $cats;
                }
            }

            return $this->success(__('Operation successful'), $alls);
        }

    }

    /**
     * 获取内容简介
     * @param  [type] $v [description]
     * @return [type]    [description]
     */
    private function getShortContent($v, $len = 40, $suffix = '...')
    {
        if (!$v) {
            return '';
        }

        return msubstr(trim(strip_tags(htmlspecialchars_decode($v))), 0, $len, 'utf-8', $suffix);
    }

    /**
     * 增加用户信息
     * @param  [type] $uinfo [description]
     * @return [type]        [description]
     */
    private function fullUserInfo($uinfo)
    {
        //用户中标统计
        $uinfo->stat_contrbute_win = (int) Db::name('mission_schedule')->where('u_id', $uinfo->u_id)->where('status', 3)->count();
        $uinfo->user_authen        = Db::name('user_authen')->where('u_id', $uinfo->u_id)->column('auth_type');
        $credit                    = Db::name('user_credit')->where('u_id', $uinfo->u_id)->field('level,integral')->find();

        if (!$credit) {
            $credit['level']    = 1;
            $credit['integral'] = 0;
        }

        $credit['level_txt'] = __(\app\api\model\UserCredit::creditLevel($credit['level'])[0]);

        $uinfo->user_credit = $credit;

        return $uinfo;

    }

    /**
     * 仲裁列表     *
     * @return \think\response\Json
     * @throws \\Exception
     */
    public function dissent()
    {

        $request = request();
        $limit   = $request->get('limit', 10);
        $w[]     = ['c.u_id', '=', $this->auth->u_id];
        if ($request->get('title')) {
            $w[] = ['b.title', 'l ike', '%' . $request->get('title') . '%'];

        }

        if ($request->get('status') != null) {
            $w[] = ['c.status', '=', $request->get('status')];

        }

        $q = cModel::alias('a')->with("userInfo")
            ->join("mission_description b", "a.mission_id=b.mission_id")
            ->join("mission_dissent c", "a.mission_id=c.mission_id ")
            ->field("c.*,b.title as mission_title")
            ->where($w)
            ->order('c.create_time', "desc");

        $ls = $q->paginate(['list_rows' => $limit, 'request' => $request->all()]);
        $q->order("a.id", "desc");
        $res    = $ls->items();
        $ids    = [];
        $status = \app\api\model\MissionDissent::getStatus();
        $res    = array_map(function ($v) use ($status, &$ids) {
            $v->status_txt = $status[$v->status];
            $v->content    = $this->getShortContent($v->content);
            $v->route      = createUrl('task', $v->mission_title, $v->mission_id);
            return $v;
        }, $res);

        $data['ls']    = $res;
        $data['total'] = $ls->total();

        return $this->success(__('Operation successful'), $data);

    }

    /**
     * 增加评论家
     */
    public function addComment()
    {
        try {
            $req        = request()->post();
            $demand_uid = cmodel::where('mission_id', $req['mission_id'])->value('u_id');
            $is_demand  = $this->auth->u_id == $demand_uid ? 1 : 0;
            $f          = Db::name('mission_sign')->where('mission_id', $req['mission_id'])->where('u_id', $this->auth->u_id)->find();
            $reply_id   = (int) $req['reply_id'];
            if (!$is_demand) {
                $ct = commentsModel::where('mission_id', $req['mission_id'])->where('u_id', $this->auth->u_id)->count();

                if ($ct > 2) {
                    throw new \Exception(__('comments_less3'), 1);

                }
            }

            if (!$is_demand && !$f) {
                throw new \Exception(__('comments_engage'), 1);
            }

            if ($is_demand && !$reply_id) {
                throw new \Exception(__('comments_not_admin'), 1);
            }

            $crt = commentsModel::create(
                [
                    'u_id'       => $this->auth->u_id,
                    'content'    => $req['content'],
                    'reply_id'   => $reply_id,
                    'mission_id' => $req['mission_id'],
                    'is_demand'  => $this->auth->u_id == $demand_uid ? 1 : 0,
                ]
            );
            //信用分
            if ($req['reply_id'] && $is_demand) {
                Credit::sceneLog($this->auth->u_id, 'replay', ['uk' => $reply_id]);

            }


            Credit::sceneLog($this->auth->u_id, 'add_comment',['uk'=>$crt->id]);


            //信用分当月
            $month_data = monthBeginAndEnd();
            if (date("Y-m-d") == date("Y-m-d", $month_data[1])) {
                $w       = [];
                $w[]     = ['mission_id', '=', $req['mission_id']];
                $w[]     = ['u_id', '<>', $demand_uid];
                $w[]     = ['create_time', 'between', implode(',', $month_data)];
                $month_t = Db::name('mission_comments')->where($w)->count();

                $w             = [];
                $w[]           = ['mission_id', '=', $req['mission_id']];
                $w[]           = ['reply_id', '>', 0];
                $w[]           = ['create_time', 'between', implode(',', $month_data)];
                $month_t_reply = Db::name('mission_comments')->where($w)->count();
                if ($month_t - $month_t_reply > 9) {
                    Credit::sceneLog($this->auth->u_id, 'noreplay10', ['uk' => date('Y-m')]);
                }
            }

            return $this->success(__('Operation successful'));

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }

    }

    /**
     * 评论列表
     */
    public function comments(Request $request)
    {
         
        $time    = time();
        $limit   = $request->get('limit', 10);

        $w = $this->getCommentsWhere($request);

        //处理排序
        $qsort       = $request->get("sort", 'id');
        $sort_define = [
            'id' => 'a.id desc',
        ];
        $order = $sort_define[$qsort];
        if (!$order) {
            return $this->error(__("Operation failed"));
        }

        $q = commentsModel::alias('a')
            ->join("user b", "a.u_id=b.u_id")
            ->join("user_profile c", "c.u_id=b.u_id", 'left')
            ->join("user_credit d", "d.u_id=b.u_id", 'left')
            ->field("a.*,b.username,c.avatar,d.level")
            ->where($w)
            ->orderRaw($order);

        $ls = $q->paginate(['list_rows' => $limit, 'request' => $request->all()]);

        $res    = $ls->items();
        $replys = $this->getReplys($request->get('mission_id'));
        $res    = array_map(function ($v) use ($replys) {
            $v["replys"] = $replys[$v['id']];
            return $v;
        }, $res);
        $data['ls']    = $res;
        $data['total'] = $ls->total();

        return $this->success(__('Operation successful'), $data);

    }

    /**
     * 评论回复
     * @param  [type] $mission_id [description]
     * @return [type]             [description]
     */
    private function getReplys($mission_id)
    {
        $res = Db::name("mission_comments")->alias("a")->join("user b", "a.u_id=b.u_id")->join("user_profile c", "c.u_id=a.u_id", 'left')->where('a.mission_id', $mission_id)->where('a.reply_id', '>', 0)->field("a.*,c.avatar,b.username")->select();
        $newres;
        foreach ($res as $key => $value) {
            $newres[$value['reply_id']][] = $value;
        }
        return $newres;
    }

    /**
     * 获取查询条件
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    private function getCommentsWhere($request)
    {
        $time = time();
        $w[]  = ['a.mission_id', '=', $request->input("mission_id")];
        $w[]  = ['a.delete_time', '=', 0];
        $w[]  = ['a.reply_id', '=', 0];

        return $w;
    }

    /**
     * 星级评比，雇主评服务方
     */
    public function estimateByDemander()
    {
        try {
            $req   = request()->post();
            $t_uid = $req['to_uid'];

            $f = cmodel::where('mission_id', $req['mission_id'])->find();

            if ($f->u_id != $this->auth->u_id) {
                throw new \Exception(__('Operation failed'));
            }
            $f = Db::name("mission_schedule")->where('mission_id', $req['mission_id'])->where("u_id", $t_uid)->find();
            if (!$f) {
                throw new \Exception(__('Operation failed'));
            }

            $f = estimateModel::where('mission_id', $req['mission_id'])->where("t_uid", $t_uid)->count();

            if ($f) {
                throw new \Exception(__('estimate ony once'));
            }

            $score = $req['score'] > 5 ? 0 : $req['score'];
            $crt   = estimateModel::create(
                [
                    'f_uid'      => $this->auth->u_id,
                    't_uid'      => $t_uid,
                    'mission_id' => $req['mission_id'],
                    'score'      => $score,
                ]
            );

            //增加信用分
            $score > 0 && Credit::sceneLog($t_uid, 'prise' . $score, ['uk' => 'prisebydemander-' . $crt->id]);

            //信用分当月
            $month_data = monthBeginAndEnd();
            $w          = [];
            $w[]        = ['t_uid', '=', $t_uid];
            $w[]        = ['score', '>', 3];
            $w[]        = ['create_time', 'between', implode(',', $month_data)];
            $t          = Db::name('mission_estimate')->where($w)->count();
            if ($t > 5) {
                Credit::sceneLog($t_uid, 'month_prise5', ['uk' => date('Y-m')]);
            }

            return $this->success(__('Operation successful'));

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 星级评比，服务方评雇主
     */
    public function estimateByService()
    {
        try {
            $req  = request()->post();
            $main = cmodel::where('mission_id', $req['mission_id'])->find();

            $f = Db::name("mission_schedule")->where('mission_id', $req['mission_id'])->where("u_id", $this->auth->u_id)->find();
            if (!$f) {
                throw new \Exception(__('Operation failed'));
            }

            $f = estimateModel::where('mission_id', $req['mission_id'])->where("f_uid", $this->auth->u_id)->count();

            if ($f) {
                throw new \Exception(__('estimate ony once'));
            }
            $score = $req['score'] > 5 ? 0 : $req['score'];

            estimateModel::create(
                [
                    'f_uid'      => $this->auth->u_id,
                    't_uid'      => $main->u_id,
                    'mission_id' => $req['mission_id'],
                    'score'      => $score,
                ]
            );

            //增加信用分
            Credit::sceneLog($main->u_id, 'prise' . $score, ['uk' => 'prisebyservice-' . $req['mission_id']]);

            //信用分当月
            $month_data = monthBeginAndEnd();
            $w          = [];
            $w[]        = ['t_uid', '=', $main->u_id];
            $w[]        = ['score', '>', 3];
            $w[]        = ['create_time', 'between', implode(',', $month_data)];
            $t          = Db::name('mission_estimate')->where($w)->count();
            if ($t > 5) {
                Credit::sceneLog($main->u_id, 'month_prise5', ['uk' => date('Y-m')]);
            }

            return $this->success(__('Operation successful'));

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

}
